package com.yonyou.crm.bpub.approval.appctrl;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.crm.bpub.approval.entity.ActionVO;
import com.yonyou.crm.bpub.approval.entity.AssigneeVO;
import com.yonyou.crm.bpub.approval.entity.DjInfoVO;
import com.yonyou.crm.bpub.approval.entity.DjTypeEnum;
import com.yonyou.crm.bpub.approval.entity.HistoryVO;
import com.yonyou.crm.bpub.approval.entity.TaskVO;
import com.yonyou.crm.bpub.approval.rmitf.IProcessRmService;
import com.yonyou.crm.bpub.detail.entity.DetailsVO;
import com.yonyou.crm.bpub.detail.rmitf.IDetailsRmService;
import com.yonyou.crm.bpub.list.entity.AppListSpecialVO;
import com.yonyou.crm.bpub.list.entity.AppListVO;
import com.yonyou.crm.bpub.list.entity.AppListValueVO;
import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;
import com.yonyou.crm.cum.customer.ctrl.OSSClientUtil;
import com.yonyou.crm.tpub.attachment.entity.AttachmentConstant;

@RequestMapping("/{version}/mbpub/approvals")
@RestController
public class AppProcessCtrl {

	@Autowired
	private IProcessRmService service;
	
	@Autowired
	private IDetailsRmService detailService;
	
	/**
	 * 将数据转化为App列表数据
	 * @param opp
	 * @return
	 * @throws CrmMessageException
	 */
	private AppListVO tranVoToAppListVO(DjInfoVO djInfo) {
		AppListVO listVO = new AppListVO();
		listVO.setId(djInfo.getDjId());
		
		List<List<AppListValueVO>> valueList = new ArrayList<>();
		List<AppListValueVO> colList = new ArrayList<>();
		AppListValueVO listValue = new AppListValueVO();
		listValue.setItemkey("name");
		listValue.setDisplayvalue(djInfo.getName());
		colList.add(listValue);
		valueList.add(colList);
		
		colList = new ArrayList<>();
		listValue = new AppListValueVO();
		listValue.setItemkey("personlist");
		List<AssigneeVO> assigneeVOs = djInfo.getApprovalUserList();
		String assigneeNames = "";
		if (assigneeVOs != null){
			for (AssigneeVO assigneeVO :assigneeVOs) {
				if (assigneeNames.equals("")) {
					assigneeNames = assigneeVO.getName();
					continue;
				}
				assigneeNames += "," + assigneeVO.getName();
			}
		}
		listValue.setDisplayvalue(assigneeNames);
		colList.add(listValue);
		valueList.add(colList);

		colList = new ArrayList<>();
		listValue = new AppListValueVO();
		listValue.setItemkey("time");
		String time = "";
		if (djInfo.getStayTimeLength() == null || djInfo.getStayTimeLength().length() == 0) {
			SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
			time = sdf.format(djInfo.getCompleteTime());
		} else {
			time = djInfo.getStayTimeLength();
		}
		listValue.setDisplayvalue(time);
		colList.add(listValue);
		valueList.add(colList);
		
		listVO.setValuelist(valueList);
		Map<String, String> hidelist = new HashMap<String, String>();
		hidelist.put("type", String.valueOf(djInfo.getDjType()));
		hidelist.put("instanceid", djInfo.getInstanceId());
		listVO.setHidelist(hidelist);;
		
		List<AppListSpecialVO> speciallist = new ArrayList<AppListSpecialVO>();
		AppListSpecialVO vo = getListPic(djInfo.getDjType());
		if (vo != null) {
			speciallist.add(vo);
		}
		listVO.setSpeciallist(speciallist);
		
		return listVO;
	}
	
	/**
	 * 将数据转化为App列表数据
	 * @param opp
	 * @return
	 * @throws CrmMessageException
	 */
	private AppListVO tranVoToAppListVO(TaskVO taskInfo) {
		AppListVO listVO = new AppListVO();
		listVO.setId(taskInfo.getDjId());
		
		List<List<AppListValueVO>> valueList = new ArrayList<>();
		List<AppListValueVO> colList = new ArrayList<>();
		AppListValueVO listValue = new AppListValueVO();
		
		listValue.setItemkey("name");
		listValue.setDisplayvalue(taskInfo.getName());
		colList.add(listValue);
		
		valueList.add(colList);
		colList = new ArrayList<>();

		listValue = new AppListValueVO();
		listValue.setItemkey("time");
		String time = "";
		if (taskInfo.getStayTimeLength() == null || taskInfo.getStayTimeLength().length() == 0) {
			SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
			time = sdf.format(taskInfo.getCompleteTime());
		} else {
			time = taskInfo.getStayTimeLength();
		}
		listValue.setDisplayvalue(time);
		colList.add(listValue);

		valueList.add(colList);
		listVO.setValuelist(valueList);
		Map<String, String> hidelist = new HashMap<String, String>();
		hidelist.put("type", String.valueOf(taskInfo.getDjType()));
		hidelist.put("instanceid", taskInfo.getInstanceId());
		hidelist.put("taskid", taskInfo.getTaskId());
		listVO.setHidelist(hidelist);
		
		List<AppListSpecialVO> speciallist = new ArrayList<AppListSpecialVO>();
		AppListSpecialVO vo = getListPic(taskInfo.getDjType());
		if (vo != null) {
			speciallist.add(vo);
		}
		listVO.setSpeciallist(speciallist);
		
		return listVO;
	}
	
	private AppListSpecialVO getListPic(int djType) {
		String picUrl = "";
		String approval = AttachmentConstant.APPROVAL_DIR;
		if (djType == DjTypeEnum.CUM_PRMT.getValue()) {
//			picUrl = "http://yonyoubucket.oss-cn-beijing.aliyuncs.com/newfile/list_customer_update.png";
			picUrl = new OSSClientUtil().getUrl(approval + "/list_customer_update.png");
		} else if (djType == DjTypeEnum.SALE_PRICE.getValue()) {
//			picUrl = "http://yonyoubucket.oss-cn-beijing.aliyuncs.com/newfile/list_on_sales.png";
			picUrl = new OSSClientUtil().getUrl(approval + "/list_on_sales.png");
		} else if (djType == DjTypeEnum.CREDICT.getValue()) {
//			picUrl = "http://yonyoubucket.oss-cn-beijing.aliyuncs.com/newfile/list_credit.png";
			picUrl = new OSSClientUtil().getUrl(approval + "/list_credit.png");
		} else if (djType == DjTypeEnum.TERMINAL_POINT_ADD.getValue()) {
//			picUrl = "http://yonyoubucket.oss-cn-beijing.aliyuncs.com/newfile/list_shop_add.png";
			picUrl = new OSSClientUtil().getUrl(approval + "/list_credit.png");
		} else if (djType == DjTypeEnum.TERMINAL_POINT_STOP.getValue()) {
//			picUrl = "http://yonyoubucket.oss-cn-beijing.aliyuncs.com/newfile/list_shop_disabled.png";
			picUrl = new OSSClientUtil().getUrl(approval + "/list_shop_disabled.png");
		} else if (djType == DjTypeEnum.CUM_PRICE.getValue()) {
//			picUrl = "http://yonyoubucket.oss-cn-beijing.aliyuncs.com/newfile/list_customer_fee.png";
			picUrl = new OSSClientUtil().getUrl(approval + "/list_customer_fee.png");
		}

		if (picUrl.isEmpty()) {
			return null;
		}
		AppListSpecialVO vo = new AppListSpecialVO();
		vo.setPosition("left");
		vo.setType("pic");
		vo.setValue(picUrl);
		return vo;
	}
	
	/*
	 * 查询已完成的审批单据
	 */
	@RequestMapping(value="/finished", method = RequestMethod.GET)
	public Object getFinished(@PathVariable("version") String version, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObject = RequestUtil.getParamObject(request);
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("page", paramObject.getInt("page"));
		paraMap.put("pageSize", paramObject.getInt("pageSize"));
		
		Page<DjInfoVO> pageDjInfo = service.getFinished(paraMap);
		List<DjInfoVO> dataList = pageDjInfo.getData();
		List<AppListVO> list = new ArrayList<AppListVO>();
		for (DjInfoVO djInfo : dataList) {
			AppListVO appListVO = tranVoToAppListVO(djInfo);
			list.add(appListVO);
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);
		
		return ResponseUtil.getObject(map);
	}
	
	/*
	 * 查询未完成的审批单据
	 */
	@RequestMapping(value="/notfinished", method = RequestMethod.GET)
	public Object getNotFinished(@PathVariable("version") String version, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObject = RequestUtil.getParamObject(request);
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("page", paramObject.getInt("page"));
		paraMap.put("pageSize", paramObject.getInt("pageSize"));
		
		Page<DjInfoVO> pageDjInfo = service.getNotFinished(paraMap);
		List<DjInfoVO> dataList = pageDjInfo.getData();
		List<AppListVO> list = new ArrayList<AppListVO>();
		for (DjInfoVO djInfo : dataList) {
			AppListVO appListVO = tranVoToAppListVO(djInfo);
			list.add(appListVO);
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);
		
		return ResponseUtil.getObject(map);
	}
	
	/*
	 * 查询流程实例
	 */
	@RequestMapping(value="/details/{id}", method = RequestMethod.GET)
	public <T extends Serializable> Object getDetail(@PathVariable("version") String version, @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObject = RequestUtil.getParamObject(request);
		int djType = paramObject.getInt("type");
		
		String module = "";
		if (djType == DjTypeEnum.CUM_PRMT.getValue()) {
			module = "cumprmts";
		} else if (djType == DjTypeEnum.CUM_PRICE.getValue()) {
			module = "cumprices";
		} else if (djType == DjTypeEnum.CREDICT.getValue()) {
			module = "credicts";
		} else if (djType == DjTypeEnum.SALE_PRICE.getValue()) {
			module = "saleprices";
		} else if (djType == DjTypeEnum.TERMINAL_POINT_ADD.getValue()) {
			module = "pointadds";
		} else if (djType == DjTypeEnum.TERMINAL_POINT_STOP.getValue()) {
			module = "pointstops";
		}
		
		DetailsVO rs = detailService.getDetailData(module, id.toString());
		return ResponseUtil.getObject(rs);
	}
	
	/*
	 * 查询审批动作列表
	 */
	@RequestMapping(value="/actions", method = RequestMethod.GET)
	public Object getActions(@PathVariable("version") String version, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObject = RequestUtil.getParamObject(request);
		String instanceId = null;
		if (paramObject.containsKey("instanceid")) {
			instanceId = paramObject.getString("instanceid");
			if (instanceId.isEmpty()) {
				instanceId = null;
			}
		}
		
		String taskId = null;
		if (paramObject.containsKey("taskid")) {
			taskId = paramObject.getString("taskid");
			if (taskId.isEmpty()) {
				taskId = null;
			}
		}
		
		List<ActionVO> list = new ArrayList<ActionVO>();
		if (instanceId != null) {
			list = service.getActions(instanceId, taskId);
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("actionlist", list);
		return ResponseUtil.getObject(map);
	}
	
	/*
	 * 执行任务
	 */
	@RequestMapping(value="/actions", method = RequestMethod.POST)
	public Object actionTask(@PathVariable("version") String version, HttpServletRequest request, HttpServletResponse response) {
		JSONObject paramObject = RequestUtil.getParamObject(request);
		Long businessId = paramObject.getLong("id");
		int djType = paramObject.getInt("type");
		String instanceId = paramObject.getString("instanceid");
		String taskId = null;
		if (paramObject.containsKey("taskid")) {
			taskId = paramObject.getString("taskid");
			if (taskId.isEmpty()) {
				taskId = null;
			}
		}
		String comment = "";
		if (paramObject.containsKey("comment")) {
			comment = paramObject.getString("comment");
		}
		
		String action = paramObject.getString("action");
		
		service.actionTask(businessId, djType, instanceId, taskId, comment, action);
		return ResponseUtil.getObject();
	}
	
	/*
	 * 查询审批历史
	 */
	@RequestMapping(value="/histories", method = RequestMethod.GET)
	public Object getHistoryTasks(@PathVariable("version") String version, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObject = RequestUtil.getParamObject(request);
		Long businessId = paramObject.getLong("id");
		int djType = Integer.parseInt(paramObject.getString("type"));
		
		List<HistoryVO> historyVOs = service.getHistoryTasks(businessId, djType, "desc");
		List<HistoryVO> rs = new ArrayList<HistoryVO>();
		for (HistoryVO historyVO : historyVOs) {
			String status = historyVO.getStatus();
			if (status.isEmpty() || status.equals("待审")) {
				historyVO.setTime("已停留" + historyVO.getTime());
			}
			historyVO.setTime(historyVO.getTime());
			rs.add(historyVO);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("historylist", rs);
		return ResponseUtil.getObject(map);
	}
	
	/*
	 * 提醒
	 */
	@RequestMapping(value="/remind", method = RequestMethod.POST)
	public Object remind(@PathVariable("version") String version, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObject = RequestUtil.getParamObject(request);
		Long businessId = paramObject.getLong("id");
		int djType = paramObject.getInt("type");
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> personlist = (List<Map<String, Object>>)paramObject.get("personlist");
		List<String> personids = new ArrayList<String>();
		for (Map<String, Object> map : personlist) {
			personids.add(map.get("id").toString());
		}
		if (personids.size() == 0) {
			throw new CrmMessageException("参数错误");
		}
		service.remind(businessId, djType, personids);
		return ResponseUtil.getObject();
	}
	
	/*
	 * 获取待办任务列表
	 */
	@RequestMapping(value="/todo", method = RequestMethod.GET)
	public Object getTasksTodo(@PathVariable("version") String version, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObject = RequestUtil.getParamObject(request);
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("page", paramObject.getInt("page"));
		paraMap.put("pageSize", paramObject.getInt("pageSize"));
		
		Page<TaskVO> pageInfo = service.getTasksTodo(paraMap);
		List<TaskVO> dataList = pageInfo.getData();
		List<AppListVO> list = new ArrayList<AppListVO>();
		for (TaskVO taskInfo : dataList) {
			AppListVO appListVO = tranVoToAppListVO(taskInfo);
			list.add(appListVO);
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);
		
		return ResponseUtil.getObject(map);
	}
	
	/*
	 * 获取已办任务列表
	 */
	@RequestMapping(value="/done", method = RequestMethod.GET)
	public Object getTasksDone(@PathVariable("version") String version, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObject = RequestUtil.getParamObject(request);
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("page", paramObject.getInt("page"));
		paraMap.put("pageSize", paramObject.getInt("pageSize"));
		
		Page<TaskVO> pageInfo = service.getTasksDone(paraMap);
		List<TaskVO> dataList = pageInfo.getData();
		List<AppListVO> list = new ArrayList<AppListVO>();
		for (TaskVO taskInfo : dataList) {
			AppListVO appListVO = tranVoToAppListVO(taskInfo);
			list.add(appListVO);
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);
		
		return ResponseUtil.getObject(map);
	}
	
	/*
	 * 获取提交单据总数
	 */
	@RequestMapping(value="/notfinishedtotal", method = RequestMethod.GET)
	public Object getProcessInstancesCount(@PathVariable("version") String version, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		int total = service.getProcessInstancesCount(null);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", total);
		return ResponseUtil.getObject(map);
	}
	
	/*
	 * 获取待办任务总数
	 */
	@RequestMapping(value="/todototal", method = RequestMethod.GET)
	public Object getTasksTodoCount(@PathVariable("version") String version, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		int total = service.getTasksCount(null);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", total);
		return ResponseUtil.getObject(map);
	}
	
	
}
